package com.tianyu.inspection.service.websocket.server;

import com.tianyu.inspection.common.Constants;
import com.tianyu.inspection.common.component.AppConstants;
import com.tianyu.inspection.entity.model.WebSocketChannelMo;
import com.tianyu.inspection.service.websocket.WebSocketHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**********************************
 * @Author YSW
 * @Description
 * @Date 2020.12.18 - 10:11
 **********************************/

@Slf4j
@Component
public class WebSocketServer implements CommandLineRunner {

    public static Map<Integer, WebSocketChannelMo> WEB_SOCKET_CHANNEL_MAP = new ConcurrentHashMap<>();

    @Resource
    private AppConstants appConstants;

    @Resource
    private WebSocketHandler webSocketHandler;

    public void start(InetSocketAddress socketAddress) {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workGroup = new NioEventLoopGroup(200);
        ServerBootstrap serverBootstrap = new ServerBootstrap()
                .group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new HttpServerCodec());
                        pipeline.addLast(new HttpObjectAggregator(64 * 1024));
                        pipeline.addLast(new ChunkedWriteHandler());
                        pipeline.addLast(new WebSocketServerProtocolHandler("/"));
                        pipeline.addLast(new IdleStateHandler(30, 0, 0));
                        pipeline.addLast(webSocketHandler);
                    }
                });
        try {
            ChannelFuture future = serverBootstrap.bind(socketAddress).sync();
            log.info("开启线程[WebSocket服务端] port -> " + socketAddress.getPort());
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    @Override
    public void run(String... args) throws Exception {
        //1、开启WebSocket线程与客户端通信
        Constants.EXECUTOR.execute(() -> start(new InetSocketAddress(appConstants.tcpWebsocketPort)));
    }
}